package com.chen.palmar.project.set;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.chen.palmar.R;
import com.chen.palmar.base.BaseActivity;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.dialog.SelectPickerDialog;
import com.chen.palmar.common.widget.view.AutoToolbar;
import com.chen.palmar.common.widget.view.SquareImageView;
import com.chen.palmar.entity.AgencyTagEntity;
import com.chen.palmar.entity.ApplyAgencyRequest;
import com.chen.palmar.project.agency.CityPickerActivity;
import com.primb.androidlibs.net.entity.HttpResultEntity;
import com.primb.androidlibs.net.entity.MessageEvent;
import com.primb.androidlibs.utils.FileUtils;
import com.squareup.picasso.Picasso;
import com.zaaach.citypicker.model.City;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import io.valuesfeng.picker.ImageSelectActivity;
import io.valuesfeng.picker.Picker;
import io.valuesfeng.picker.engine.GlideEngine;
import rx.Subscription;

/**
 * @author Chen
 * @date 2018/1/9
 * 功能描述：
 */

public class ApplyAgencyActivity extends BaseActivity {
    private static final int REQUEST_CODE_IMG = 41;
    @Bind(R.id.title_bar)
    TextView titleBar;
    @Bind(R.id.tool_bar)
    AutoToolbar toolBar;
    @Bind(R.id.et_apply_title)
    EditText etApplyTitle;
    @Bind(R.id.et_apply_desc)
    EditText etApplyDesc;
    @Bind(R.id.tv_apply_tag1)
    TextView tvApplyTag1;
    @Bind(R.id.tv_apply_tag2)
    TextView tvApplyTag2;
    @Bind(R.id.tv_apply_tag3)
    TextView tvApplyTag3;
    @Bind(R.id.et_apply_user)
    EditText etApplyUser;
    @Bind(R.id.et_apply_phone)
    EditText etApplyPhone;
    @Bind(R.id.et_apply_brand)
    EditText etApplyBrand;
    @Bind(R.id.tv_apply_address)
    TextView tvApplyAddress;
    @Bind(R.id.iv_apply_img)
    SquareImageView ivApplyImg;
    private ApplyAgencyRequest request;
    private Uri uri;
    private static final int REQUEST_CODE_PICK_CITY = 2;
    public static final int EVENT_AGENCY_CODE = 1456435;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    public void init() {
        toolBar.setNavigationOnClickListener(v -> ApplyAgencyActivity.this.finish());

        titleBar.setText("经销商发布");

        request = new ApplyAgencyRequest();

        ivApplyImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Picker.from(ApplyAgencyActivity.this).singleChoice().enableCamera(true).setEngine(new GlideEngine()).forResult(REQUEST_CODE_IMG);
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_apply_agency;
    }

    private void showTagDialog(int id) {
        SelectPickerDialog<AgencyTagEntity.DataBean> dialog = new SelectPickerDialog<>();
        dialog.setListener(new SelectPickerDialog.OnPickedListener<AgencyTagEntity.DataBean>() {
            @Override
            public void onPickCompleted(AgencyTagEntity.DataBean dataDesc) {
                switch (id) {
                    case R.id.tv_apply_tag1:
                        tvApplyTag1.setText(dataDesc.getName());
                        request.setChannel1(dataDesc.getChannelId() + "");
                        break;
                    case R.id.tv_apply_tag2:
                        tvApplyTag2.setText(dataDesc.getName());
                        request.setChannel2(dataDesc.getChannelId() + "");
                        break;
                    case R.id.tv_apply_tag3:
                        tvApplyTag3.setText(dataDesc.getName());
                        request.setChannel3(dataDesc.getChannelId() + "");
                        break;
                }
            }
        });
        dialog.show(getSupportFragmentManager());
        getTagList(dialog);
    }

    private void getTagList(SelectPickerDialog dialog) {
        Subscription subscribe = DataCenter.agencyTagList().subscribe(new HttpSubscriber<AgencyTagEntity>(this, null) {
            @Override
            public void onNext(AgencyTagEntity tagListEntity) {
                if (null != dialog && dialog.isVisible()) {
                    dialog.setDateList(tagListEntity.getData());
                }
            }
        });
        subscription.add(subscribe);
    }

    private void applyInfo() {
        request.setContacts(etApplyUser.getText().toString());
        request.setMobile(etApplyPhone.getText().toString());
        request.setDesc(etApplyDesc.getText().toString());
        request.setBrand(etApplyBrand.getText().toString());
//        request.setName(etApplyTitle.getText().toString());
        String channel = "";
        if (!TextUtils.isEmpty(request.getChannel1())) {
            channel = request.getChannel1();
        }
        if (!TextUtils.isEmpty(request.getChannel2())) {
            channel = channel + (!TextUtils.isEmpty(channel) ? "," : "") + request.getChannel2();
        }
        if (!TextUtils.isEmpty(request.getChannel3())) {
            channel = channel + (!TextUtils.isEmpty(channel) ? "," : "") + request.getChannel3();
        }
        request.setChannel(channel);
        if (!checkParams()) {
            return;
        }
        Subscription subscribe = DataCenter.applyAgency(request).subscribe(new HttpSubscriber<HttpResultEntity>(this, showLoading("发布中")) {

            @Override
            public void onNext(HttpResultEntity applyInfoEntity) {
                showToast(applyInfoEntity.getMessage());
                EventBus.getDefault().post(new MessageEvent(EVENT_AGENCY_CODE));
                ApplyAgencyActivity.this.finish();
            }
        });
        subscription.add(subscribe);
    }

    private boolean checkParams() {
//        if (TextUtils.isEmpty(request.getName())) {
//            showToast("请输入经销商名称");
//            return false;
//        } else
            if (TextUtils.isEmpty(request.getDesc())) {
            showToast("请输入基本介绍");
            return false;
        } else if (TextUtils.isEmpty(request.getAddress_id())) {
            showToast("请选择城市");
            return false;
        }
//        else if (TextUtils.isEmpty(request.getChannel())) {
//            showToast("请选择发布标签");
//            return false;
//        }
        else if (TextUtils.isEmpty(request.getContacts())) {
            showToast("请输入联系人");
            return false;
        } else if (TextUtils.isEmpty(request.getMobile())) {
            showToast("请输入联系电话");
            return false;
        } else if (TextUtils.isEmpty(request.getBrand())) {
            showToast("请输入品牌名称");
            return false;
        } else {
            return true;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_IMG && resultCode == Activity.RESULT_OK) {
            List<Uri> imgList = data.getParcelableArrayListExtra(ImageSelectActivity.EXTRA_RESULT_SELECTION);
            uri = imgList.get(0);
            Picasso.with(this).load(uri).placeholder(R.mipmap.occupy_icon).error(R.mipmap.occupy_icon).into(ivApplyImg);
            request.setImg(FileUtils.getRealPathFromUri(this, uri));
        } else if (requestCode == REQUEST_CODE_PICK_CITY && resultCode == RESULT_OK) {
            if (data != null) {
                City city = (City) data.getSerializableExtra(CityPickerActivity.KEY_PICKED_CITY);
                tvApplyAddress.setText(city.getName());
                request.setAddress_id(city.getAddessId() + "");
            }
        }
    }

    @OnClick({R.id.tv_apply_tag1, R.id.tv_apply_tag2, R.id.tv_apply_tag3, R.id.tv_apply_address, R.id.btn_apply_info})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_apply_tag1:
            case R.id.tv_apply_tag2:
            case R.id.tv_apply_tag3:
                showTagDialog(view.getId());
                break;
            case R.id.tv_apply_address:
                startActivityForResult(new Intent(this, CityPickerActivity.class), REQUEST_CODE_PICK_CITY);
                break;
            case R.id.btn_apply_info:
                applyInfo();
                break;
        }
    }
}
